#! /usr/bin/env python2

# Author: Raymond Barrett
# Email: barretrj@tcd.ie

import socket
import pygame
import pygame.camera
from multiprocessing import Queue

#image_res = (1040,680)
#image_res = (1040,680)
#image_res = (950, 540)
image_res = (512, 384)

def serve(address, que):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(address)
        sock.listen(1)
        print "Your IP address is: ", socket.gethostbyname(socket.gethostname())
    
        # initialise the display window
        pygame.init()
        pygame.camera.init()
        cameras = pygame.camera.list_cameras()
        print cameras
        cam = pygame.camera.Camera(cameras[0], image_res)
        cam.start()
        
        print "Server Waiting for client on port", address[1]
        
        while 1:
            img = cam.get_image()
            img = pygame.transform.flip(img,1,0)

            client_socket, address = sock.accept()
            img = pygame.transform.scale(img,image_res)
            data = pygame.image.tostring(img, 'RGB')
            # Place frame on queue
            if que.empty():
                que.put(data)
            # Prepend the frame with the length of the data so that 
            # the client knows how much data to receive
            data = str(len(data)) + '::'+ data
            client_socket.sendall(data)
            #print "Frame size", len(data), "sent."
    except KeyboardInterrupt:
        print "Exiting..."
    finally:
        sock.close()
        print "Program Exited."

if __name__ == "__main__":
    address = ('127.0.1.1', 50000)
    serve(address, Queue(1))
